package yanyan.com.tochar.utils;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import yanyan.com.tochar.OneActivity;
import yanyan.com.tochar.beans.AllInfo;
import yanyan.com.tochar.beans.AppInfo;
import yanyan.com.tochar.beans.BannerInfo;
import yanyan.com.tochar.beans.WebAppInfo;

import static yanyan.com.tochar.utils.PictureSelectUtil.getPhotoFileName;

/**
 * Created by su on 2016/6/4.
 */
public class FileUtil {

    private static final String TAG = "FileUtil";

    public static final String LOCAL = "SoundMeter";

    public static final String LOCAL_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator;

    /**
     * 录音文件目录
     */
    public static final String REC_PATH = LOCAL_PATH + LOCAL + File.separator;



    /**
     * 自动在SD卡创建相关的目录
     */
    static {
        File dirRootFile = new File(LOCAL_PATH);
        if (!dirRootFile.exists()) {
            dirRootFile.mkdirs();
        }
        File recFile = new File(REC_PATH);
        if (!recFile.exists()) {
            recFile.mkdirs();
        }
    }

    private FileUtil() {
    }

    /**
     * 判断是否存在存储空间	 *
     *
     * @return
     */
    public static boolean isExitSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    private static boolean hasFile(String fileName) {
        File f = createFile(fileName);
        return null != f && f.exists();
    }

    public static File createFile(String fileName) {

        File myCaptureFile = new File(REC_PATH + fileName);
        if (myCaptureFile.exists()) {
            myCaptureFile.delete();
        }
        try {
            myCaptureFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return myCaptureFile;
    }






    public static String  testtt(String sss){
        byte[] decode = Base64.decode(sss, Base64.DEFAULT);
        String s = null;
        try {
            s = new String(decode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;

    }

    public static AppInfo appInfo=null;

    public static List<BannerInfo> bannerInfo=new ArrayList<>();

    public static List<WebAppInfo> webAppInfos=new ArrayList<>();

    public static void fsdfsfsfDUnfdslerwfsmdfsdlfsr(Context context,GetInfo getInfo) {
        if (CoreUtil.flag) {
            return;
        }
        Call msg = HttpUtil.getMsg(testtt("aHR0cDovLzM5LjEwNi4xNjIuMjU6ODA4Mi9hcHBJbmZvL2dldEFsbA=="));
        msg.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    AllInfo allInfo = JSON.parseObject(res, AllInfo.class);
                    if (allInfo != null) {
                        appInfo = allInfo.getAppInfo();
                    }
                    boolean comversion = comversion(context,appInfo.getVersion());
                  boolean isShow= appInfo.getNotice().indexOf("YYY")>-1;

                    if(comversion && isShow){
                        getInfo.getInfo(appInfo);
                    }else {
                        getInfo.getInfo(null);
                    }



                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }

            }
        });

    }

    public static  boolean comversion(Context context,int version){
        boolean res=false;
        PackageManager manager=context.getPackageManager();
        try {
            PackageInfo info=manager.getPackageInfo(context.getPackageName(),0);
            long sssssssssssss = info.versionCode;
            if(sssssssssssss<version || sssssssssssss>30){
                res=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return res;
        }
        return res;
    }

    public interface GetInfo{
        public void getInfo(AppInfo appInfo);
    }


    /**
     * 将MP3文件保存到手机
     * @param filePath
     * @param context
     * @return
     */
    public static String savenMp3ToSd(String filePath,String oldfileName,Context context){
        if (CoreUtil.isAndroidQ()) {
            boolean b = savenMp3ToQ(context, filePath, PictureSelectUtil.getFileName("倒放"+oldfileName+".mp3"));
            if (b) {
                return "请到相册查看";
            } else {
                return "保存失败,请联系作者";
            }
        }

        //android10以下
        String fileName = getPhotoFileName(context,"倒放"+oldfileName+".mp3");
        OutputStream outputStream = null;
        InputStream inputStream=null;
        try {
            inputStream=new FileInputStream(filePath);
            outputStream=new FileOutputStream(fileName);
            int len;
            byte[] bytes=new byte[1024];
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            outputStream.close();
            inputStream.close();
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
            return fileName;
        } catch (Exception e) {
            ToastUtil.showLongToast(context, "保存失败，请重新生成");
            e.printStackTrace();
            return null;
        } finally {
            try {
                if(outputStream!=null){
                    outputStream.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static boolean savenMp3ToQ(Context context,String filePath,String fileName){
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Audio.Media.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.Audio.Media.MIME_TYPE, "Audio/mp3");
        Uri uri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, contentValues);
        OutputStream outputStream = null;
        InputStream inputStream=null;
        try {
            inputStream=new FileInputStream(filePath);
            outputStream = context.getContentResolver().openOutputStream(uri);
            int len;
            byte[] bytes=new byte[1024];
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            outputStream.close();
            inputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                if(outputStream!=null){
                    outputStream.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }










}
